<script setup lang="ts">
import { useRouter } from 'vue-router';
import type { GoodsList } from '@/types';
import { addCartPost } from '@/services';

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  joinCarData: {
    type: Object,
  },
  buttonType: {
    type: Number,
    // 1：展示立即购买和加入购物车; 2:展示立即购买; 3:展示加入购物车
    default: 1,
  },
});
const $router = useRouter();
const loading = ref(false);
const joinPopData = ref<GoodsList>({} as GoodsList);
const $emit = defineEmits(['update:modelValue']);
const show = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    $emit('update:modelValue', value);
  },
});
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      joinPopData.value = JSON.parse(JSON.stringify(props.joinCarData)) as GoodsList;
    }
  },
  { immediate: true },
);
const onBuyClick = () => {
  if (!joinPopData.value.stock || joinPopData.value.stock < joinPopData.value.amount!) {
    showToast('库存不足');
    return;
  }
  if (joinPopData.value.salesFlag === 'NO') {
    showToast('无权限');
    return;
  }
  $router.push({
    path: '/settlement',
    query: { amount: joinPopData.value.amount, goodsId: joinPopData.value.goodsId },
  });
};

const onCarClick = async () => {
  if (!joinPopData.value.stock || joinPopData.value.stock < joinPopData.value.amount!) {
    showToast('库存不足');
    return;
  }
  loading.value = true;
  const params = {
    amount: joinPopData.value.amount,
    factoryName: joinPopData.value.factoryName,
    price: joinPopData.value.goodsSalesPrice,
    stock: joinPopData.value.stock,
    goodsId: joinPopData.value.goodsId,
    goodsImg: joinPopData.value.goodsImg.split(',')[0],
    goodsName: joinPopData.value.goodsName,
    supplierId: joinPopData.value.supplierId,
    unit: joinPopData.value.unit,
    goodsSubtitle: joinPopData.value.goodsSubtitle,
    goodsDesc: null,
    goodsSpec: null,
    goodsSpecId: null,
    goodsCategoryName:
      joinPopData.value.goodsCatNameFirst + '-' + joinPopData.value.goodsCatNameSecond,
  };
  const { message, err } = await addCartPost(params);
  if (err) {
    showToast(err);
    return;
  }
  showToast(message);
  $emit('update:modelValue', false);
  loading.value = false;
};

const onStepChange = async (value: any, order: any) => {
  if (value < order.minimumQuantity) {
    showToast('低于最小数量');
  }
};
const onOverLimit = (_: any, order: any) => {
  showToast(`最低起订量为${order.minimumQuantity}`);
};
const getCategoryText = (props: any) => {
  if (!props) return '';
  const prefix =
    props.apparatusCategoryLevel === 1
      ? ''
      : props.apparatusCategoryLevel === 2
        ? 'II类医疗器械 / '
        : 'III类医疗器械 / ';
  return `${prefix}${props.apparatusCategoryName}`;
};
</script>

<template>
  <van-popup v-model:show="show" position="bottom" destroy-on-close :style="{ maxHeight: '70%' }">
    <div class="join-car-top">
      <div class="top-left"></div>
      <div class="goods_box">
        <van-image :src="joinPopData.goodsImg?.split(',')[0]" round />
        <div class="right_spc">
          <van-text-ellipsis rows="2" class="text-ellipsis" :content="joinPopData.goodsName" />
          <div class="right_price">
            <div class="goods_price">
              <span>￥</span>
              <span class="price_num">{{ joinPopData.goodsSalesPrice }}</span>
            </div>
            <van-stepper
              @change="(value) => onStepChange(value, joinPopData)"
              @overlimit="(value) => onOverLimit(value, joinPopData)"
              v-model="joinPopData.amount"
              integer
              :min="joinPopData.minimumQuantity"
            />
          </div>
        </div>
      </div>
    </div>
    <div v-if="joinPopData.isCombo === 'NO'">
      <div class="goods-spc">产品属性</div>
      <van-cell>
        <template #title>
          <div>器械类别</div>
        </template>
        <template #value>
          <div>{{ getCategoryText(joinPopData.apparatusCategory) }}</div>
        </template>
      </van-cell>
      <van-cell
        v-for="item in joinPopData.goodsExpandparamValueList"
        :key="item.expandparamValueId"
      >
        <template #title>
          <div>{{ item.expandparamName }}</div>
        </template>
        <template #value>
          <div>{{ item.expandparamValueName }}</div>
        </template>
      </van-cell>
    </div>
    <div v-if="joinPopData.isCombo === 'YES'">
      <div class="goods-spc">套装商品</div>
      <van-cell v-for="item in joinPopData.comboItemList" :key="item.comboGoodsId">
        <template #title>
          <div>{{ item.goodsName }}</div>
        </template>
        <template #value>
          <div>{{ `x${item.num}` }}</div>
        </template>
      </van-cell>
    </div>
    <div :class="{ 'pop-button': true, 'button-type': buttonType === 1 }">
      <van-button
        v-if="buttonType === 1"
        @click="onBuyClick"
        color="#E89000"
        round
        text="立即购买"
      />
      <van-button
        v-if="buttonType === 1"
        :loading="loading"
        @click="onCarClick"
        text="加入购物车"
        color="#00BA9F"
        round
      />
      <van-button
        v-if="buttonType === 2"
        :loading="loading"
        @click="onCarClick"
        text="加入购物车"
        color="#E89000"
        round
        block
      />
      <van-button
        v-if="buttonType === 3"
        :loading="loading"
        @click="onBuyClick"
        text="立即购买"
        color="#E89000"
        round
        block
      />
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
.join-car-top {
  width: 100%;
  height: 120px;
  padding: 16px;
  display: flex;

  .goods_box {
    width: 100%;
    height: 96px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .van-image {
      width: 88px;
      height: 88px;
      border-radius: 8px;
    }

    .right_spc {
      width: 219px;
      height: 88px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .van-text-ellipsis {
        color: #000000;
        font-size: 14px;
        font-weight: 500;
      }

      .right_price {
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .goods_price {
          font-size: 12px;
          color: #e86600;
          font-weight: 400;

          .price_num {
            font-size: 16px;
            font-weight: 500;
          }
        }
      }
    }
  }

  :deep(.van-stepper__minus) {
    width: 20px;
    height: 20px;
    color: #787878;
    background: transparent;
  }

  :deep(.van-stepper__plus) {
    width: 20px;
    height: 20px;
    color: #787878;
    background: transparent;
  }

  :deep(.van-stepper__input) {
    width: 29px;
    height: 18px;
    border-radius: 4px;
    background: #ebebeb;
  }
}

.goods-spc {
  width: 100%;
  height: 42px;
  font-size: 14px;
  font-weight: 500;
  line-height: 42px;
  padding-left: 16px;
  color: #000000;
}

.pop-button {
  width: 100%;
  height: 40px;
  margin: 48px 0 16px 0;
  padding: 0 16px;
  display: flex;
  justify-content: space-around;
  align-items: center;

  .van-button {
    height: 40px;
  }
}

.button-type {
  .van-button {
    width: 167px;
  }
}

.text-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.van-cell__title) {
  min-width: 88px;
  max-width: 88px;
  color: #787878;
  font-size: 12px;
  font-weight: 400;
}

:deep(.van-cell__value) {
  font-size: 12px;
  padding-left: 16px;
  font-weight: 400;
  text-align: left;
  color: #222222;
}
</style>
